<template>
  <div class="v2-table wh-full">
    <div  class="pd-tb-10-px">
      <TableHead :config="tableForm.tableHead" @newAdd="handlerAdd" @search="search"></TableHead>
    </div>
    <el-table :data="tableData" border
              :default-expand-all="tableForm.isTree"
              size="small"
              ref="elTable"
              :row-key="tableForm.rowKey"
              :tree-props="tableForm.treeProps"
              v-bind="$attrs"
              @row-click="rowClick"
              @row-dblclick="rowDblclick"
              @select="select"
              class="wh-full">
      <template>
        <el-table-column
            v-for="(col ) in tableColumns"
            :prop="col.key"
            :align="nvl(col.align,'center')"
            :label="col.title"
            :width="nvl(col.width, {})">
        </el-table-column>
        <el-table-column
            v-for="(col ) in btnColumns"
            :align="nvl(col.align,'center')"
            :label="col.title"
            :width="nvl(col.width, {})">
          <template v-slot:default="{row,$index}">
            <el-button :type="nvl(btn.btnType,'text')"
                       size="small"
                       v-for="(btn) in nvl(col.buttons,[])"
                       @click="handlerRowClick(btn,$index)">{{btn.title}}</el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
        class="mar-tb-10px"
        v-if="tableForm.showPage"
        :align="tableForm.pageAlign"
        background
        layout="prev, pager, next"
        :current-page="page.current"
        :total="page.total">
    </el-pagination>
    <dialog-form
        :form-data="innerFormData"
        :width="tableForm.formWidth"
        :inline="tableForm.formInline"
        :columns="formColumns"
        @submit="formSubmit"
        v-model="dialogStatus"></dialog-form>
  </div>
</template>

<script>
import TableForm from "components/table/TableForm.js";
import commons from "utils/commons";
import http from "network/http";
import ApiResponse from "utils/ApiResponse";
import TableHead from "components/table/TableHead.vue";

export default {
  name: "TableForm" ,
  components:{TableHead},
  props:{
    config: {
      type: Object ,
      default:()=>{
        return {}
      }
    },
    data:{
      type: Array ,
      default:()=>{
        return []
      }
    },
    formData:{
      type: Object ,
      default:()=>{
        return {}
      }
    }
  },
  data(){
    return {
      tableForm:null ,
      tableData: [],
      page: null ,
      dialogStatus: false ,
      currentBtn: {} ,
      currentRow: null ,
      innerFormData:{}
    }
  },
  created() {
    this.tableForm = new TableForm(this.config);
    this.innerFormData = Object.assign({},this.formData)
    this.page = this.tableForm.page
  },
  computed:{
    tableColumns(){
      return this.tableForm.columns.getTableColumns().filter(col=>col.type !== 'buttons')
    },
    btnColumns(){
      return this.tableForm.columns.getTableColumns().filter(col=>col.type === 'buttons')
    },
    formColumns(){
      return this.tableForm.columns.getFormColumns()
    }
  },
  mounted() {
    this.tableData = this.data ;
    if(!this.tableForm.lazy){
      if(!commons.isVoid(this.tableForm.url)){
        this.request()
      }
    }

  },
  methods:{
    getFirst(){
      if(!commons.isVoid(this.tableForm.url)){
        this.request()
      }
    },
    select(selection, row){
      console.log(selection, row)
    },
    getSelectCurrentRow(){
      return this.currentRow ;
    },
    rowClick(row, column, event){
      this.currentRow = row ;
    },
    rowDblclick(row, column, event){
      this.$emit("row-dblclick",row)
    },
    handlerAdd({button}){
      this.dialogStatus = true ;
      this.currentBtn = button
      this.innerFormData = Object.assign({},this.formData)
    },
    search({button,formData}){
      this.page.current = 1 ;
      http({
        url: this.tableForm.url,
        method: this.tableForm.method,
        data:  {...this.getParams(formData) }
      }).then(this.handlerResponse)
    },
    handlerRowClick(btn,index){
      if(commons.isFun(btn.callback)){
        btn.callback(this.tableData[index],index,this.tableData)
      }else if(!commons.isVoid(btn.url)){
        if(btn.type === "delete"){
          let {id} = btn ;
          if(commons.isVoid(this.tableData[index][id])){
            this.tableData.splice(index, 1)
            btn.after && btn.after(this.tableData[index])
          }else{
            this.$confirm('确定删除该记录吗?, 是否继续?', '操作提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.tableForm.delete(btn,this.tableData[index])
                  .then(res=>{
                    ApiResponse.init(res).print();
                    if(commons.isFun(btn.after)){
                      btn.after(this.tableData[index])
                    }else{
                      this.request() ;
                    }
                  })
            }).catch(()=>{})
          }
        }else if(btn.type === "update"){
          let data = this.tableData[index] ;
           this.innerFormData = data ;
           this.currentBtn = btn
          this.dialogStatus = true
        }
      }
    },
    formSubmit(formData){
      let btn = this.currentBtn ;
      this.tableForm.handlerBtn(btn,formData,()=>{
        this.tableForm.request(btn,formData).then(res=>{
          ApiResponse.init(res).print();
          if(commons.isFun(btn.after)){
            btn.after(res)
          }else{
            this.request() ;//刷新
          }
        })
      })
    },
    request(){
      http({
        url: this.tableForm.url,
        method: this.tableForm.method,
        data: this.getParams()
      }).then(this.handlerResponse)
    },
    handlerResponse(res) {
      ApiResponse.init(res).ok((data)=>{
        let respData = this.getResponseData(data) ;
        this.tableData = respData.row ;
        this.page.total = respData.total
      })
    },
    getParams(formData = {}){
      let params = this.tableForm.params
      let p = commons.isFun(params) ? params():{};
      let data = {data: {...p,...formData}}
      if(this.tableForm.showPage){
        data.current = this.page.current ;
        data.size = this.page.size
        return data ;
      }else{
        return {...p,...formData}
      }

    },
    getResponseData(data){
      if(this.tableForm.showPage){
        return {
          row: data.records  ,
          total: data.total
        }
      }
      return {
        row: data ,
        total: data.length
      }
    },
    nvl(a,b){
      return commons.nvl(a,b)
    },
    refresh(){
      this.page.current = 1 ;
      this.request() ;
    }
  }
}
</script>

<style scoped>

</style>